﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Mono.Cecil;

namespace NDasm.Core
{
    public static class CoreHelper
    {
        /// <summary>
        /// Returns MethodDefinition for given assembly file and method name
        /// </summary>
        /// <param name="module">Module definition</param>
        /// <param name="methodName">Method name in format FullTypeName.MethodName</param>        
        public static MethodDefinition GetMethod(ModuleDefinition module, string methodName)
        {
            string typeName, shortMethodName;
            ParseMethodName(methodName, out typeName, out shortMethodName);            
            TypeDefinition type = module.GetType(typeName);
            return type != null ? type.Methods.Where(m => m.Name == shortMethodName).FirstOrDefault() : null;
        }

        /// <summary>
        /// Parses method name in Namespace.Type.Method format
        /// </summary>        
        private static void ParseMethodName(string method, out string typeName, out string methodName)
        {
            int index = method.LastIndexOf('.');
            typeName = method.Substring(0, index);
            methodName = method.Substring(index + 1, method.Length - index - 1);
            string shortTypeName = typeName.Split('.').Last();
            if (shortTypeName == methodName)
                methodName = ".ctor";
        }        
    }
}
